package com.scenic.orderservice.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.scenic.common.bean.*;
import com.scenic.common.exception.ScenicSpotException;
import com.scenic.common.service.OrderService;
import com.scenic.common.service.ScenicSpotService;
import com.scenic.common.service.UserService;
import com.scenic.orderservice.mapper.CartMapper;
import com.scenic.orderservice.mapper.OrderDetailMapper;
import com.scenic.orderservice.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private CartMapper cartMapper;
    @DubboReference
    private UserService userService;
    @DubboReference
    private ScenicSpotService scenicSpotService;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void insert(HashMap<String ,Object> ticketVo) throws ScenicSpotException {
        //创建订单对象
        Order order = new Order();
        //生成订单id
        String orderId = IdUtil.getSnowflakeNextIdStr();
        //设置订单id
        order.setId(orderId);
        order.setCreateTime(new Date());
        order.setPreOrderDate((Date) ticketVo.get("preOrderDate"));
        //生成订单
        order.setUserId((Integer) ticketVo.get("userId"));
        order.setPayType(0);
        order.setStatus(0);
        orderMapper.insert(order);
        //生成订单
        List<LinkedHashMap> ticketMaps = (List<LinkedHashMap>) ticketVo.get("tickets");
        List<OrderVo> tickets = new ArrayList<>();

        for (LinkedHashMap ticketMap : ticketMaps) {
            OrderVo ticket = new OrderVo();
            // 手动映射字段
            ticket.setCount((Integer) ticketMap.get("count"));
            ticket.setTicketType((Integer) ticketMap.get("ticketType"));
            ticket.setPrice(new BigDecimal(String.valueOf(ticketMap.get("price"))));
            ticket.setPayPwd((String) ticketMap.get("payPwd"));
            tickets.add(ticket);
        }
        for (OrderVo ticket : tickets) {
            //获取商品信息
            Long scenicSpotId = new Long((String) ticketVo.get("scenicSpotId"));
            ScenicSpot scenicSpot = scenicSpotService.selectById(scenicSpotId);
            if (scenicSpot == null){
                throw new ScenicSpotException("景区不存在，无法生成订单");
            }
            //添加详情
            OrderDetail orderDetail = new OrderDetail();

            orderDetail.setScenicSpotId(scenicSpotId);
            orderDetail.setOrderId(orderId);
            orderDetail.setCount(ticket.getCount());
            orderDetail.setTicketType(ticket.getTicketType());
            orderDetail.setPrice(ticket.getPrice());

            orderDetailMapper.insert(orderDetail);
        }
        ticketVo.put("orderId",orderId);

    }

    @Override
    public boolean update(Order order, Integer userId) throws ScenicSpotException {
        //用户修改订单
        //判断订单是否属于该用户
        Order o = orderMapper.selectById(order.getId());
        if (!o.getUserId().equals(userId)) {
            throw new ScenicSpotException("订单不属于该用户无法修改！");
        }
        //修改订单
        return orderMapper.update(order) == 1;
    }

    @Override
    public boolean delete(Integer id) {
        //todo 用户删除订单
        return false;
    }

    @Override
    public List<Order> selectByUserId(Integer userId) throws ScenicSpotException {
        //判断是否为合法的用户
        if (userService.selectById(userId) == null) {
            throw new ScenicSpotException("用户不存在");
        }
        List<Order> list = orderMapper.selectByUserId(userId);
        if (list.isEmpty()) {
            throw new ScenicSpotException("该用户没有订单");
        }
        return list;
    }

    @Override
    public Order selectById(String id, Integer userId) throws ScenicSpotException {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new ScenicSpotException("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new ScenicSpotException("订单不属于该用户，无法支付！");
        }
        //查询订单详情对应的商品的信息
        for (OrderDetail orderDetail : order.getOrderDetailList()) {
            orderDetail.setScenicSpot(scenicSpotService.selectById(orderDetail.getScenicSpotId()));
        }
        order.setUser(userService.selectById(order.getUserId()));
        return order;
    }

    @Override
    public PageInfo<Order> selectByCondition(Order condition, Integer pageNum, Integer pageSize) throws ScenicSpotException {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> list = orderMapper.selectByCondition(condition);
        //为所有订单设置用户
        for (Order order : list) {
            order.setUser(userService.selectById(order.getUserId()));
            //为所有的订单详情设置商品
            for (OrderDetail detail : order.getOrderDetailList()) {
                detail.setScenicSpot(scenicSpotService.selectById(detail.getScenicSpotId()));
            }
        }

        if (list.isEmpty()) {
            throw new ScenicSpotException("未查询到订单");
        }
        PageInfo<Order> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void pay(HashMap<String ,Object> ticketVo) throws ScenicSpotException {
        //根据orderId查询订单
        Order order = orderMapper.selectById((String) ticketVo.get("orderId"));
        //判断订单是否存在
        if (order == null) {
            throw new ScenicSpotException("订单不存在无法支付！");
        }
        //判断订单是否属于该用户
        if (!order.getUserId().equals(ticketVo.get("userId"))) {
            throw new ScenicSpotException("订单不属于当前用户，无法支付！");
        }
        //判断订单当前是否未支付状态
        if (!order.getStatus().equals(0)) {
            throw new ScenicSpotException("订单状态错误，无法支付");
        }
        //设置status 为1
        order.setStatus(1);
        //设置payType为0 余额支付
        order.setPayType(0);
        orderMapper.update(order);

        //根据有用户id查询用户
        User user = userService.selectById(order.getUserId());
        //判断支付密码是否正确
        String payPwdMysql = user.getPayPassword();
        if (payPwdMysql == null) {
            throw new ScenicSpotException("没有设置支付密码，请设置之后再下单！");
        }
        //对输入的密码进行验证
        String md5Pwd = SecureUtil.md5(SecureUtil.md5((String) ticketVo.get("payPwd") + user.getSalt()));
        if (!md5Pwd.equals(payPwdMysql)) {
            throw new ScenicSpotException("支付密码错误，无法支付");
        }
        //计算当前订单的总金额 orderDetail数量*价格
        BigDecimal sum = new BigDecimal("0");
        for (OrderDetail orderDetail : order.getOrderDetailList()) {
            BigDecimal count = new BigDecimal(orderDetail.getCount());
            BigDecimal price = orderDetail.getPrice();
            sum = sum.add(price.multiply(count));
        }

        //判断余额充足 bigDecimal如何比较大小
        if (user.getMoney().compareTo(sum) < 0) {
            throw new ScenicSpotException("余额不足，无法支付");
        }
        //扣除金额
        user.setMoney(user.getMoney().subtract(sum));

        userService.update(user);
    }

    //@Override
    //public List<Order> selectByUserAll(Order condition, Integer userId) throws MallException {
    //    List<Order> orderList = orderMapper.selectByUserAll(condition);
    //    //判断订单是否属于该用户
    //    for (Order order : orderList) {
    //        if (!order.getUserId().equals(userId)) {
    //            throw new MallException("订单不属于该用户！");
    //        }
    //        for (OrderDetail orderDetail : order.getOrderDetailList()) {
    //            orderDetail.setGoods(scenicSpotService.selectById(orderDetail.getScenicSpot()));
    //        }
    //    }
    //    return orderList;
    //}
}
